<template>
  <div class="app-container">
    <ResizeBox :treeData="treeData" @pitchOnData="pitchOnData">
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="80px"
      >
        <el-form-item label="管控方式:">
          <el-select v-model="queryParams.dataSrc" placeholder="请选择管控方式">
            <el-option
              v-for="item in dict.type.data_src"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item prop="measureType" label="管控措施:">
          <el-select
            v-model="queryParams.measureType"
            placeholder="请选择管控措施"
          >
            <el-option
              v-for="item in dict.type.measure_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="措施描述:">
          <el-input
            v-model="queryParams.describe"
            placeholder="请输入措施描述"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="排查内容:">
          <el-input
            v-model="queryParams.content"
            placeholder="请输入排查内容"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="任务类型:">
          <el-select
            v-model="queryParams.taskType"
            placeholder="请选择任务类型"
          >
            <el-option
              v-for="item in dict.type.task_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="启用状态:">
          <el-select
            v-model="queryParams.taskStatus"
            placeholder="请选择启用状态"
          >
            <el-option
              v-for="item in taskStatusData"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
          <el-button
            type="primary"
            icon="el-icon-refresh"
            size="mini"
            @click="getTaskList"
            v-if="expandRowKeys.length > 0"
            >刷新任务列表</el-button
          >
        </el-form-item>
      </el-form>

      <!-- 措施列表 -->
      <el-table
        v-loading="measureLoading"
        :data="measureList"
        highlight-current-row
        style="width: 100%"
        :expand-row-keys="expandRowKeys"
        :row-key="handleRowKey"
        @expand-change="expandChangeTask"
      >
        <el-table-column type="expand">
          <template slot-scope="superProps">
            <!-- 任务列表 -->
            <el-table
              v-loading="taskLoading"
              :data="taskList"
              highlight-current-row
              border
              style="width: 100%;"
            >
              <el-table-column type="index" width="50" align="center" />
              <el-table-column
                label="检查部门"
                prop="checkByDeptName"
                align="center"
              />
              <el-table-column
                label="检查人"
                prop="checkByNames"
                show-overflow-tooltip
              />
              <el-table-column
                label="任务类型"
                prop="taskType"
                align="center"
              />
              <el-table-column
                label="开始时间"
                prop="startTime"
                align="center"
              />
              <el-table-column label="启用/停止" prop="status" align="center">
                <template slot-scope="props">
                  <el-switch
                    v-model="props.row.status"
                    @change="handleUpStatus(props.row)"
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
              >
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleUpdate(scope.row, superProps.row)"
                    v-hasPermi="['syf:task:edit']"
                    >修改</el-button
                  >
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['syf:task:remove']"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>

        <el-table-column
          label="安全风险对象"
          align="center"
          prop="objectName"
          show-overflow-tooltip
        />
        <el-table-column
          label="安全风险单元"
          align="center"
          prop="unitName"
          show-overflow-tooltip
        />
        <el-table-column
          label="风险事件"
          align="center"
          prop="accidentName"
          show-overflow-tooltip
        />
        <el-table-column label="管控方式" align="center" prop="dataSrc" />
        <el-table-column
          label="管控措施"
          align="center"
          prop="measureType"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            {{
              `${scope.row.measureType}/${scope.row.measureSubType}/${scope.row.measureOtherType}`
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="措施描述"
          align="center"
          prop="description"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          label="排查内容"
          prop="content"
          show-overflow-tooltip
        />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-plus"
              @click="handleAdd(scope.row)"
              v-hasPermi="['syf:task:add']"
              >新增</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getMeasureList"
      />

      <!-- 添加或修改排查定时任务对话框 -->
      <el-dialog
        :title="title"
        :visible.sync="open"
        width="1000px"
        append-to-body
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="140px">
          <el-card class="box-card" style="margin-bottom: 20px">
            <el-descriptions :column="3" title="基本信息">
              <el-descriptions-item :span="1" label="安全风险对象">{{
                row.objectName
              }}</el-descriptions-item>
              <el-descriptions-item :span="2" label="安全风险单元">{{
                row.unitName
              }}</el-descriptions-item>
              <el-descriptions-item :span="3" label="风险事件">{{
                row.accidentName
              }}</el-descriptions-item>
              <el-descriptions-item :span="1" label="管控方式">{{
                row.dataSrc
              }}</el-descriptions-item>
              <el-descriptions-item :span="2" label="管控措施">{{
                `${row.measureType}/${row.measureSubType}/${row.measureOtherType}`
              }}</el-descriptions-item>
              <el-descriptions-item :span="3" label="措施描述">{{
                row.description
              }}</el-descriptions-item>
              <el-descriptions-item :span="3" label="排查内容">{{
                row.content
              }}</el-descriptions-item>
            </el-descriptions>
          </el-card>

          <hr />

          <el-row>
            <el-col :span="12">
              <el-form-item label="检查人部门" prop="checkByDept">
                <treeselect
                  v-model="form.checkByDept"
                  :options="deptOptions"
                  :show-count="true"
                  placeholder="请选择检查人部门"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="任务类型" prop="taskType">
                <el-select
                  v-model="form.taskType"
                  style="width: 100%"
                  placeholder="请选择任务类型"
                >
                  <el-option
                    v-for="item in dict.type.task_type"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row v-show="form.taskType != '0' && form.taskType != null">
            <el-col :span="24">
              <el-form-item
                label="包保任务对应项"
                prop="taskNum"
                :rules="
                  form.taskType != '0' && form.taskType != null
                    ? {
                        required: true,
                        message: '请选择包保任务对应项',
                        trigger: 'blur',
                      }
                    : {}
                "
              >
                <el-select
                  v-model="form.taskNum"
                  style="width: 100%"
                  placeholder="请选择包保任务对应项"
                >
                  <el-option
                    v-for="item in taskNumData"
                    :key="item.value"
                    :label="handleTaskNumLabel(item.label)"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row v-if="form.checkByDept != null">
            <el-col :span="24">
              <el-form-item label="检查人" prop="checkByList">
                <el-select
                  v-model="form.checkByList"
                  filterable
                  multiple
                  placeholder="请选择检查人"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in userList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <hr />

          <el-row>
            <el-col :span="24">
              <el-form-item prop="cycleType" label="定时任务类型">
                <el-radio v-model="form.cycleType" label="incremental"
                  >周期</el-radio
                >
                <el-radio v-model="form.cycleType" label="daily">每日</el-radio>
                <el-radio v-model="form.cycleType" label="weekdays"
                  >工作日</el-radio
                >
                <el-radio v-model="form.cycleType" label="holiday"
                  >节假日</el-radio
                >
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="18" v-show="cycleShow">
              <el-form-item prop="cycleUnit" label="排查周期:">
                <div>
                  <el-input-number
                    min="1"
                    v-model.number="form.cycle"
                    type="text"
                  />
                  <el-select
                    v-model="form.cycleUnit"
                    placeholder="请选择时间单位"
                    style="width: 50%"
                  >
                    <el-option
                      v-for="item in dict.type.time_unit"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item prop="startTime" label="开始时间:">
                <el-date-picker
                  v-model="form.startTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :picker-options="pickerOptions"
                  placeholder="请选择开始时间"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="18">
              <el-form-item prop="lastCycleUnit" label="排查任务时长:">
                <div class="zq">
                  <el-input-number
                    min="1"
                    v-model.number="form.lastCycle"
                    type="text"
                  />
                  <el-select
                    v-model="form.lastCycleUnit"
                    placeholder="请选择时间单位"
                    style="width: 50%"
                  >
                    <el-option
                      v-for="item in dict.type.time_unit"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item prop="previousPeriodsNum" label="生成往期任务数:">
                <el-input-number
                  min="0"
                  v-model.number="form.previousPeriodsNum"
                  type="text"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </ResizeBox>
  </div>
</template>

<script>
import {
  listTask,
  getTask,
  delTask,
  addOrUpdate,
  upStatus,
} from "@/api/syf/check/task";
import { listMeasure } from "@/api/syf/risk/measure";
import { evaluationTree } from "@/api/syf/tree";
import { deptTreeSelect, listUser } from "@/api/system/user";
import ResizeBox from "@/components/syf/ResizeBox/index";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Task",
  components: { ResizeBox, Treeselect },
  dicts: [
    "data_src",
    "task_type",
    "measure_type",
    "task_num_main",
    "task_num_technology",
    "task_num_operate",
    "time_unit",
  ],
  data() {
    return {
      // 遮罩层
      measureLoading: true,
      taskLoading: false,
      cycleShow: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      measureList: [],
      // 排查定时任务表格数据
      taskList: [],
      // 风险树
      treeData: [],
      taskNumData: [],
      //用户集合
      userList: [],
      // 部门树选项
      deptOptions: undefined,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        measureId: undefined,
        detailIds: [],
        dataSrc: undefined,
        measureType: undefined,
        describe: undefined,
        content: undefined,
        taskType: undefined,
        taskStatus: undefined,
        status: true,
      },
      taskQuery: {
        measureId: undefined,
        status: undefined,
        taskType: undefined,
      },
      taskStatusData: [
        { label: "启用", value: 1 },
        { label: "停止", value: 0 },
      ],
      // 列表展开的行
      expandRowKeys: [],
      row: {},
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        taskType: [
          { required: true, message: "任务类型不能为空", trigger: "blur" },
        ],
        checkByDept: [
          { required: true, message: "检查人部门不能为空", trigger: "blur" },
        ],
        cycleType: [
          { required: true, message: "请选择定时任务类型", trigger: "blur" },
        ],
        checkByList: [
          {
            validator: (rule, value, callback) => {
              if (!this.form.ifPost && (value == null || value.length === 0)) {
                callback(new Error("请选择排查人"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        startTime: [
          { required: true, message: "请选择开始时间", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (new Date(value).getTime() < new Date().getTime()) {
                callback(new Error("开始时间需大于当前时间"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        cycleUnit: [
          {
            required: true,
            message: "请输入排查周期及时间单位",
            trigger: "blur",
          },
          {
            validator: (rule, value, callback) => {
              if (value == "7" && this.form.cycle > 1) {
                callback(new Error("周期单位为年时，周期仅可设为1！"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
      //限制可选时间大于当前时间
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() <= new Date().getTime() - 24 * 60 * 60 * 1000;
        },
      },
    };
  },
  watch: {
    "form.taskType"(val) {
      if (val != "0") {
        let taskType = "";
        switch (val) {
          case "1":
            taskType = "task_num_main";
            break;
          case "2":
            taskType = "task_num_technology";
            break;
          case "3":
            taskType = "task_num_operate";
            break;
        }
        if (taskType != "") {
          this.taskNumData = this.dict.type[taskType];
        } else {
          this.taskNumData = [];
        }
      }
    },
    "form.cycleType"(val) {
      if ("daily" == val) {
        this.cycleShow = false;
        this.form.cycle = 1;
        this.form.cycleUnit = "4";
      } else {
        this.cycleShow = true;
      }
    },
    "form.checkByDept"(val) {
      this.userList = [];
      if (val != null) {
        listUser({ deptId: val }).then((res) => {
          res.rows.forEach((user) => {
            this.userList.push({
              label: user.nickName,
              value: user.userId,
            });
          });
        });
      }
    },
  },
  created() {
    this.getTreeData();
    this.getMeasureList();
    this.getDeptTree();
  },
  methods: {
    /** 查询管控措施列表 */
    getMeasureList() {
      this.measureLoading = true;
      listMeasure(this.queryParams).then((response) => {
        this.measureList = response.rows;
        this.total = response.total;
        this.measureLoading = false;
      });
    },
    /** 查询排查定时任务列表 */
    getTaskList() {
      this.taskLoading = true;
      listTask(this.taskQuery).then((response) => {
        this.taskList = response.data;
        this.taskLoading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        measureId: null,
        checkByDept: null,
        checkBys: null,
        taskType: null,
        taskNum: null,
        cycleType: null,
        cycle: null,
        cycleUnit: null,
        lastCycle: null,
        lastCycleUnit: null,
        startTime: null,
        previousPeriodsNum: null,
        status: null,
        excursionTime: null,
        actualStartTime: null,
        lastActualStarttime: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        delFlag: null,
        firmId: null,
        checkByList: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getMeasureList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        measureId: undefined,
        detailIds: [],
        dataSrc: undefined,
        measureType: undefined,
        describe: undefined,
        content: undefined,
        taskType: undefined,
        taskStatus: undefined,
        status: true,
      };
      this.taskQuery = {
        measureId: undefined,
        status: undefined,
        taskType: undefined,
      };
      this.expandRowKeys = [];
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.row = row;
      this.form.measureId = row.id;
      this.open = true;
      this.title = "添加排查定时任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row, superRow) {
      this.reset();
      this.row = superRow;
      const id = row.id;
      getTask(id).then((response) => {
        this.form = response.data;
        this.form.checkByList = JSON.parse(this.form.checkBys);
        this.open = true;
        this.title = "修改排查定时任务";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let checkByNames = "";
          this.form.checkByList.forEach((c) => {
            this.userList.forEach((u) => {
              if (c == u.value) {
                checkByNames += u.label + ";";
                return;
              }
            });
          });
          this.form.checkByNames = checkByNames;
          addOrUpdate(this.form).then((response) => {
            this.$modal.msgSuccess(
              this.form.id != null ? "新增成功" : "修改成功"
            );
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal
        .confirm('是否确认删除排查定时任务编号为"' + id + '"的数据项？')
        .then(function () {
          return delTask(id);
        })
        .then(() => {
          this.getTaskList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    /** 查询树数据 */
    getTreeData() {
      evaluationTree().then((res) => {
        this.treeData = res.data;
      });
    },
    //选中树节点
    pitchOnData(val) {
      let detailIds = [];
      val.forEach((item) => {
        detailIds.push(item.id);
      });
      this.queryParams.detailIds = detailIds;
      this.handleQuery();
    },
    handleRowKey(row) {
      return row.id;
    },
    //处理下拉项过长问题
    handleTaskNumLabel(label) {
      if (label.length < 55) return label;
      return label.substring(0, 55) + "...";
    },
    //展开列表
    expandChangeTask(row, expandedRows) {
      this.expandRowKeys = [];
      if (expandedRows != null) {
        this.taskLoading = true;
        this.taskQuery = {
          measureId: row.id,
          status: this.queryParams.taskStatus,
          taskType: this.queryParams.taskType,
        };
        listTask(this.taskQuery).then((response) => {
          this.expandRowKeys = [expandedRows[expandedRows.length - 1].id];
          this.taskList = response.data;
          this.taskLoading = false;
        });
      } else {
        this.taskList = [];
      }
    },
    //启动\关闭定时任务
    handleUpStatus(row) {
      const text = row.status ? "启用任务" : "停止任务";
      this.$confirm("是否" + text + "?")
        .then((_) => {
          upStatus(row.id).then((res) => {
            this.$message({
              message: text + "成功！",
              type: "success",
            });
          });
        })
        .catch((_) => {
          this.$message({
            message: text + "失败",
            type: "error",
          });
          row.status = !row.status;
        });
    },
  },
};
</script>
